package org.dxw.common;

import cn.hutool.db.sql.SqlUtil;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser;
import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlSchemaStatVisitor;
import com.alibaba.druid.sql.parser.SQLStatementParser;
import com.alibaba.druid.stat.TableStat;
import com.baomidou.mybatisplus.annotation.InterceptorIgnore;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.dxw.common.enums.TableChangeEnum;
import org.dxw.vo.TableChangeMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.util.*;

/**
 * @Author dxw
 * @Date 2023/11/20 23:00
 * @Description
 * todo dxw
 */
@Intercepts({
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
@Slf4j
public class MybatisInterceptor implements Interceptor {

    @Autowired
    private TableChangeHandler tableChangeHandler;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        try{
            // 获取原始方法的参数列表
            Object[] args = invocation.getArgs();
            // 获取第一个参数，即StatementHandler对象
            MappedStatement mappedStatement = (MappedStatement) args[0];
            SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
            String sql = mappedStatement.getBoundSql(args[1]).getSql();
            String changeType = null;
            //获取第一个表名，这个表才是我们新增修改删掉记录的表
            String tableName = getAllTableNameBySQL(sql).get(0);
            if (sqlCommandType == SqlCommandType.INSERT) {
                // 新增操作
                changeType = TableChangeEnum.INSERT;
            } else if (sqlCommandType == SqlCommandType.UPDATE) {
                // 修改操作
                changeType = TableChangeEnum.UPDATE;
            } else if (sqlCommandType == SqlCommandType.DELETE) {
                // 删除操作
                changeType = TableChangeEnum.DELETE;
            } else {
                // 其他操作，不做拦截处理，直接继续执行原始方法
            }
            if(TableChangeEnum.isInterested(tableName, changeType)){
                TableChangeEnum[] values = TableChangeEnum.values();
                TableChangeMsg tableChangeMsg = new TableChangeMsg();
                tableChangeMsg.setTableName(tableName);
                tableChangeMsg.setChangeType(changeType);
                tableChangeHandler.addMsg(tableChangeMsg);
            }
        }catch (Exception e){
            log.warn("mybatis拦截器解析表名错误", e);
        }
        //继续执行原始方法
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        // 可以设置一些自定义的属性，这里可以用于配置一些参数。
        // ...
    }

    private List<String> getAllTableNameBySQL(String sql) {
        SQLStatementParser parser = new MySqlStatementParser(sql);
        // 使用Parser解析生成AST，这里SQLStatement就是AST
        SQLStatement sqlStatement = parser.parseStatement();
        MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor();
        sqlStatement.accept(visitor);
        Map<TableStat.Name, TableStat> tables = visitor.getTables();
        List<String> allTableName = new ArrayList<>();
        for (TableStat.Name t : tables.keySet()) {
            allTableName.add(t.getName());
        }
        return allTableName;
    }

}
